package net.java.fixrouter.operations;

import net.java.nioserver.operations.OpRead;
import net.java.nioserver.utils.ChannelUtil;
import net.java.nioserver.utils.Pool;
import net.java.fixrouter.FixMessagePipeline;

import java.nio.channels.SocketChannel;
import java.nio.ByteBuffer;
import java.io.IOException;

/**
 * @author Leonid Shlyapnikov
 */
public class RawDataReadOperation implements OpRead {

    private final Pool<ByteBuffer> byteBufferPool;

    private final FixMessagePipeline pipeline;

    public RawDataReadOperation(Pool<ByteBuffer> byteBufferPool, FixMessagePipeline pipeline) {
        this.byteBufferPool = byteBufferPool;
        this.pipeline = pipeline;
    }

    public boolean handle(SocketChannel channel) throws IOException, InterruptedException {
        final ByteBuffer buffer = byteBufferPool.take();

        try {
            boolean runMore = ChannelUtil.readOneLineFromChannel(channel, buffer);
            if (!runMore) {
                return false; // far end disconnected, cannot send anything back
            }

            pipeline.put(buffer);

            return runMore;
        } finally {
            byteBufferPool.release(buffer);
        }
    }

    public String toString() {
        return getClass().getSimpleName();
    }
}
